package cn.juque.jdfsystem.controller.message;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.juque.common.base.BaseRequestVO;
import cn.juque.common.base.BaseResponseVO;
import cn.juque.common.constants.MessageEnum;
import cn.juque.common.utils.FastJsonUtil;
import cn.juque.jdfsystem.cache.ConfigInfoCache;
import cn.juque.jdfsystem.cache.RegisterInfoCache;
import cn.juque.jdfsystem.controller.BaseController;
import cn.juque.jdfsystem.entity.RegisterInfo;
import cn.juque.jdfsystem.enums.ConfigCodeEnum;
import cn.juque.jdfsystem.vo.registerinfo.RegisterInfoListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>RegisterInfoMessageController</li>
 * </ul>
 * @date 2024-01-30
 **/
@Slf4j
@Controller
@RequestMapping("/jdf/message/register")
public class RegisterInfoMessageController extends BaseController {

    @Resource
    private RegisterInfoCache registerInfoCache;

    @Resource
    private ConfigInfoCache configInfoCache;

    /**
     * 查看文件
     */
    @PostMapping(value = "/load")
    @ResponseBody
    public BaseResponseVO<List<RegisterInfoListVO>> load(@RequestBody BaseRequestVO<String> request) {
        this.registerInfoCache.putRegister(this.parseBody(request.getParam()));
        List<RegisterInfo> list = this.registerInfoCache.listAllRegister();
        List<RegisterInfoListVO> voList = BeanUtil.copyToList(list, RegisterInfoListVO.class);
        return new BaseResponseVO<>(MessageEnum.OK, voList);
    }

    private List<RegisterInfo> parseBody(String content) {
        if(CharSequenceUtil.isEmpty(content)) {
            return new ArrayList<>(0);
        }
        String key = this.configInfoCache.getValue(ConfigCodeEnum.REGISTER_AES_KEY.getCode());
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, Base64.decode(key));
        String body = aes.decryptStr(content);
        return FastJsonUtil.parseArray(body, RegisterInfo.class);
    }
}
